const requestData = async (url: string, params:any, options: any) => {
    let loading:any;
    if(process.client&&ElLoading&&!options.loading){
        // loading=ElLoading.service({fullscreen:options.fullscreen||true,text:options.text||'加载中...',background:'rgba(0,0,0,0.7)'})
        // loading?.open?.()
    }
    const fn=options.type=='client'?$fetch:useFetch;
    const headers=useRequestHeaders(['authorization'])
    const login=useLoginStore();
    headers.authorization = login.token;
    options.method=(options.method||'get').toUpperCase();
    const baseUrl=useRuntimeConfig().public.apiBase
    url=`${baseUrl}${url}`;
    const forms:any={
        default:()=>{},
        method:options.method,
        onRequest({ options }:any) {

        },
        onRequestError({ request, options, error }:any) {
            // 处理请求错误
            loading?.close?.();
            ElMessage.error('请求错误:'+error.message)
        },
        onResponse({ request, response, options }:any) {
            // 处理响应数据
            loading?.close?.();
            response._data=typeof response._data=="string"?JSON.parse(response._data):response._data
            if(response._data.code==200){
                // ElMessage.success(response._data.message)
            }else if(response._data.code==401){
                login.setToken('')
                login.setInfo({})
                login.setVisible(true)
                login.setLoginType('login')
                navigateTo('/index.html')
            }else{
                ElMessage.error(response._data.message)
            }
        },
        onResponseError({ request, response, options }:any) {
            loading?.close?.();
            response._data=typeof response._data=="string"?JSON.parse(response._data):response._data
            ElMessage.error('响应错误:'+response._data.message)
            // 处理响应错误
        },
        server:options.type=='server',
        lazy:false,
        watch:false,
        headers,
    };
   if(options.method=='GET'){
       forms.params=params;
   }else{
       forms.body=JSON.stringify(params)
   }

   // @ts-ignore
    return fn(url,forms)
}
export const useGet = async (url: string, params: any={}, options: any={}) => await requestData(url, params, { method: 'get',type:'client',...options })

export const usePost = async (url: string, params: any={}, options: any={}) => await requestData(url, params, { method: 'post',type:'client', ...options })
export const useServerGet = async (url: string, params: any={}, options: any={}) => await requestData(url, params, { method: 'get',type:'server', ...options })
export const useServerPost = async (url: string, params: any={}, options: any={}) => await requestData(url, params, { method: 'post',type:'server', ...options })
export const showFieldsError=(fields:any)=>{
    for(let key in fields){
      return ElMessage.error(fields[key][0].message)
    }
}
export function debounceFn(func:Function, delay:number) {
    let timer; // 设置一个定时器变量

    return function() {
        clearTimeout(timer); // 清除之前的定时器

        timer = setTimeout(() => {
            func.apply(this, arguments); // 使用 apply 将 this 和参数传递给原始函数
        }, delay);
    };
}
export function throttleFn(func, delay) {
    let lastTime = null; // 记录上一次执行的时间

    return function() {
        const now = Date.now(); // 获取当前时间

        if (lastTime && now - lastTime < delay) {
            return; // 若两次调用时间小于指定的延迟时间，直接返回
        } else {
            func.apply(this, arguments); // 否则执行原始函数

            lastTime = now; // 更新上一次执行的时间
        }
    };
}